package com.zhiyou.aifeng.smart_machine

import android.os.Bundle
import android.widget.ImageView
import com.alibaba.android.arouter.launcher.ARouter
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.invisible
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.base.visible
import com.zhiyou.aifeng.common.helper.get
import com.zhiyou.aifeng.common.helper.getString
import com.zhiyou.aifeng.common.helper.getTimeString
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadLinear
import com.zhiyou.aifeng.common_ui.base.refresh
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.model.CommonData
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.utils.onTabSelectedListener
import com.zhiyou.aifeng.utils.setEmptyIcon
import com.zhiyou.aifeng.viewmodel.RepairViewModel
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import kotlinx.android.synthetic.main.layout_title_msg.*
import net.idik.lib.slimadapter.SlimAdapter

class MessageActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_message)
        setTransparentAndToolbar(isDarkFont = false)
        initTitle()
    }

    override fun getViewModel() = get<RepairViewModel>()

    override fun initTitle(title: String, name: String, divider: Boolean) {
        initTabLayout()
        initList()

        msg_right.oneClick { if (mList.isNotEmpty()) readAll() }
    }

    private fun initTabLayout() {
        msg_tab.apply {
            onTabSelectedListener {
                onTabSelected {
                    if (mList.isNotEmpty()) {
                        mList.clear()
                        mAdapter.notifyDataSetChanged()
                    }

                    when (it!!.position) {
                        0 -> {
                            msg_right.visible()
                            initAdapter(0)
                        }
                        1 -> {
                            msg_right.invisible()
                            initAdapter(1)
                        }
                    }

                    getViewModel().cancelRequest()
                    getViewModel().delay { updateList(it.position) }
                }
            }
            addTab(newTab().setText("消息"), true)
            addTab(newTab().setText("公告"), false)
        }
    }

    private fun initList() {
        empty_img.setEmptyIcon()
        empty_hint.text = "暂无相关消息信息！"
        swipe_refresh.refresh {
            when (msg_tab.selectedTabPosition) {
                0 -> getData(1)
                1 -> getSystemList(1)
            }
        }
        recycle_list.apply {
            loadLinear(baseContext, swipe_refresh) {
                if (!isLoadingMore) {
                    isLoadingMore = true
                    getData(pageNum)
                }
            }
        }
    }

    private fun initAdapter(position: Int) {
        when (position) {
            0 -> {
                mAdapter = SlimAdapter.create()
                    .register<CommonData>(R.layout.item_msg_list) { data, injector ->

                        val index = mList.indexOf(data)

                        injector.text(R.id.item_msg_title, data.title)
                            .text(R.id.item_msg_content, data.message)
                            .text(R.id.item_msg_time, data.create_date.getTimeString("yyyy-MM-dd"))
                            .with<ImageView>(R.id.item_msg_img) {
                                it.setImageResource(
                                    if (data.status == "0") R.mipmap.icon_msg02
                                    else R.mipmap.icon_msg03
                                )
                            }
                            .clicked(R.id.item_msg) {
                                if (data.status != "1") {
                                    getViewModel().request(
                                        requestUrl = BaseUrl.msgRead,
                                        params = *arrayOf(
                                            "uid" to getString("userId"),
                                            "id" to data.id
                                        ),
                                        onResult = {
                                            data.status = "1"
                                            mAdapter.notifyItemChanged(index)
                                        }
                                    )
                                }
                            }
                    }
                    .attachTo(recycle_list)
            }
            else -> {
                mAdapter = SlimAdapter.create()
                    .register<CommonData>(R.layout.item_msg_list02) { data, injector ->
                        injector.text(R.id.item_msg_title, data.title)
                            .text(R.id.item_msg_content, data.message)
                            .text(R.id.item_msg_time, data.createDate.getTimeString("yyyy-MM-dd"))
                            .clicked(R.id.item_msg) {
                                ARouter.getInstance()
                                    .build(Routers.deal)
                                    .withString("title", "详情")
                                    .withString("hint", data.title)
                                    .withString("content", data.message)
                                    .withString("time", data.createDate.getTimeString("yyyy-MM-dd"))
                                    .navigation()
                            }
                    }
                    .attachTo(recycle_list)
            }
        }
    }

    private fun readAll() {
        getViewModel().request(
            requestUrl = BaseUrl.msgAll,
            params = *arrayOf(
                "uid" to getString("userId"),
                "type" to 2
            ),
            onResult = { updateList(0) }
        )
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getMsgList(
            userId = getString("userId"),
            index = index,
            onSuccess = {
                mList.apply {
                    if (index == 1) {
                        clear()
                        pageNum = index
                    }
                    addItems(it)
                    if (it.count() > 0) pageNum++
                }

                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                isLoadingMore = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun getSystemList(index: Int) {
        getViewModel().getSystemList(
            userId = getString("userId"),
            index = index,
            onSuccess = {
                mList.apply {
                    if (index == 1) {
                        clear()
                        pageNum = index
                    }
                    addItems(it)
                    if (it.count() > 0) pageNum++
                }

                mAdapter.updateData(mList)
            },
            onFinally = {
                swipe_refresh.isRefreshing = false
                isLoadingMore = false
                empty_view.apply { if (mList.isEmpty()) visible() else gone() }
            }
        )
    }

    private fun updateList(position: Int) {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        when (position) {
            0 -> getData(pageNum)
            1 -> getSystemList(pageNum)
        }
    }

}